package com.atguigu.chapter07;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * TODO 水位连续 5s 上升，告警
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/6 9:12
 */
public class Flink24_ProcessFunction_TimerPractice {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forMonotonousTimestamps()
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );

        KeyedStream<WaterSensor, String> sensorKS = sensorDS.keyBy(sensor -> sensor.getId());

        SingleOutputStreamOperator<String> resultDS = sensorKS
                .process(
                        new KeyedProcessFunction<String, WaterSensor, String>() {

                            private long timerTs = 0L;
                            private int lastVC = 0;

                            @Override
                            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                                // 注册定时器: 不要每条来都注册
                                if (timerTs == 0) {
                                    timerTs = ctx.timestamp() + 5000L;
                                    ctx.timerService().registerEventTimeTimer(timerTs);
                                }
                                // 判断水位上升情况
                                if (value.getVc() <= lastVC) {
                                    // 删除之前的定时器
                                    ctx.timerService().deleteEventTimeTimer(timerTs);

                                    // 以当前时间为基准，重新注册一个定时器
                                    timerTs = ctx.timestamp() + 5000L;
                                    ctx.timerService().registerEventTimeTimer(timerTs);
                                }

                                // 更新水位值（无论上升还是下降都要）
                                lastVC = value.getVc();

                            }

                            @Override
                            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                                out.collect("传感器" + ctx.getCurrentKey() + "在" + timestamp + "监测到水位连续5s上涨，快跑！");
                                // 重置保存的时间
                                timerTs = 0L;
                            }
                        }
                );

        resultDS.print();


        env.execute();
    }
}
